package com.sgffsg.mygirl.controller;

import com.sgffsg.mygirl.entity.ResultEntity;
import com.sgffsg.mygirl.repository.GirlRepository;
import com.sgffsg.mygirl.entity.Girl;
import com.sgffsg.mygirl.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * Created by work on 2017/9/24.
 */
@RestController
public class GirlController {

    @Autowired
    private GirlRepository girlRepository;

//    @GetMapping(value = "/girls")
//    public List<Girl> getGirlList(){
//        return girlRepository.findAll();
//    }

    @GetMapping(value = "/girls")
    public ResultEntity getGirlList(){
        return ResultUtil.success(girlRepository.findAll());
    }

//    /**
//     * 添加一个女生
//     * @param cup
//     * @param age 年龄
//     * @return
//     */
//    @PostMapping(value = "/add")
//    public Girl girlAdd(@RequestParam("cupSize") String cup,
//                          @RequestParam("age") Integer age){
//        Girl girl=new Girl();
//        girl.setAge(age);
//        girl.setCupSize(cup);
//        return girlRepository.save(girl);
//
//    }

    @PostMapping(value = "/add")
    public ResultEntity<Girl> girlAdd(@Valid Girl girl, BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            return ResultUtil.error(1,bindingResult.getFieldError().getDefaultMessage());
        }
        girl.setAge(girl.getAge());
        girl.setCupSize(girl.getCupSize());
        return ResultUtil.success(girlRepository.save(girl));
    }

//    //查询一个女生
//    @GetMapping(value = "/{id}")
//    public Girl findOneGirl(@PathVariable("id") Integer id){
//        return girlRepository.findOne(id);
//    }

    @GetMapping(value = "/{id}")
    public ResultEntity findOneGirl(@PathVariable("id") Integer id){
        return ResultUtil.success(girlRepository.findOne(id));
    }

    //更新一个女生
    @PostMapping(value = "/{id}")
    public Girl girlUpdate(@PathVariable("id") Integer id,
                           @RequestParam("cupSize") String cup,
                           @RequestParam("age") Integer age){
        Girl girl=girlRepository.findOne(id);
        girl.setCupSize(cup);
        girl.setAge(age);
        return girlRepository.save(girl);
    }

    //删除一个女生
//    @DeleteMapping(value = "/{id}")
//    public void deleteOneGirl(@PathVariable("id") Integer id){
//        girlRepository.delete(id);
//    }

    //删除一个女生
    @DeleteMapping(value = "/{id}")
    public ResultEntity deleteOneGirl(@PathVariable("id") Integer id){
        girlRepository.delete(id);
        return ResultUtil.successt();
    }

    //通过年龄查询女生列表
    @GetMapping(value = "/age/{age}")
    public List<Girl> girlListByAge(@PathVariable("age") Integer age){
        return girlRepository.findByAge(age);
    }

}
